class ArticlesController < ApplicationController
  before_filter :find_article, :except => [ :index, :new, :create ]
  before_filter :login_required, :except => [ :index, :show ]
  
  def index
    @articles = Article.find(:all, :order => 'created_at DESC')
  end

  def new
  end

  def create
    @article = Article.new(params[:article])
    @article.user = current_user
    @article.save!
    redirect_to article_url(@article)
  rescue
    render :action => 'new'
  end


  def show
  end

  def edit
  end

  def update
    @article.attributes = params[:article]
    @article.user = current_user
    @article.save!
    redirect_to article_url(@article)
  rescue
    render :action => 'edit'
  end

  def destroy
    @article.destroy if request.delete?
    redirect_to articles_url
  end

  def delete
  end

  protected
    def find_article
      @article = Article.find(params[:id])
    end
  
    # only article author and admin can delete it
    def authorized?
      return true if ['index', 'new', 'create' ].include?(action_name)
      current_user == @article.user || current_user.login == 'admin'
    end

end
